package cn.micai.core.controller.admin;

import cn.micai.common.controller.BaseController;
import cn.micai.common.page.Pagination;
import cn.micai.core.bean.product.Brand;
import cn.micai.core.bean.user.Admin;
import cn.micai.core.bean.user.Buyer;
import cn.micai.core.query.user.AdminQuery;
import cn.micai.core.query.user.BuyerQuery;
import cn.micai.core.service.user.BuyerService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.Date;

/**
 * 用户(购买人)管理
 *
 * @author zhaoxinguo on 2017/8/4.
 */
@Controller
@RequestMapping(value = "/control")
public class BuyerController extends BaseController{

    @Autowired
    private BuyerService buyerService;

    //列表
    @RequestMapping(value = "/buyer/list.do")
    public String list(Integer pageNo,String name,ModelMap model){
        //分页的参数
        StringBuilder params = new StringBuilder();

        //购买者条件对象
        BuyerQuery buyerQuery = new BuyerQuery();

        //1.判断条件是否为Null
        if(StringUtils.isNotBlank(name)){
            buyerQuery.setUsername(name);
            // 要求模糊查询
//            buyerQuery.setUsernameLike(name);
            params.append("name=").append(name);
            //回显查询条件
            model.addAttribute("name", name);
        }

        //设置页号
        buyerQuery.setPageNo(Pagination.cpn(pageNo));
        //设置每页数
        buyerQuery.setPageSize(5);
        //按照ID倒排
        buyerQuery.orderbyUsername(false);

        //4.加载带有分页的商品
        Pagination pagination = buyerService.getBuyerListWithPage(buyerQuery);
        //分页页面展示
        pagination.pageView("/control/buyer/list.do", params.toString());
        model.addAttribute("pagination", pagination);

        return "buyer/list";
    }

    //去添加页面
    @RequestMapping(value = "/buyer/toAdd.do")
    public String toAdd(ModelMap model){
        return "buyer/add";
    }

    //管理员添加
    @RequestMapping(value = "/buyer/add.do")
    public String add(Buyer buyer){
        //传管理员对象到Service
        buyer.setPassword(mD5Pwd.encode(buyer.getPassword()));
        buyer.setRegisterTime(new Date());
        buyerService.addBuyer(buyer);
        return "redirect:/control/buyer/list.do";
    }

    //去修改页面
    /*@RequestMapping(value = "/buyer/toEdit.do")
    public String toEdit(Integer id, ModelMap model){
        Buyer buyer = buyerService.getBuyerByKey(id);
        model.addAttribute("buyer", buyer);
        return "buyer/edit";
    }*/

}
